// packageA/pages/cashService/operator/operator.js
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog'
const { request } = require('../../../utils/request');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabActive: 0,
    stationList: wx.getStorageSync('userInfo').stationList,
    stationSelected: wx.getStorageSync('userInfo').stationSelected,
    showStationSelector: false,
    stationIndex: 0,

    bagList: [],
    result: [], //checkbox结果
    allChecked: false, //全选标记
    sumMoney: 0, //合计钱数

    userActive: '0',
    minDate: new Date('2021/12/01').getTime(),
    maxDate: new Date().getTime(),
    queryOrder: {
      startId: '',
      orderStatus: 1,
      date: '',
      minDate: '',
      maxDate: '',
      minMoney: 0,
      maxMoney: ''
    },
    queryDone: {
      startId: '',
      orderStatus: 2,
      date: '',
      minDate: '',
      maxDate: '',
      minMoney: 0,
      maxMoney: ''
    },
    selectMode: '',
    selectTimeStr: '按时间筛选',
    showTimeSelector: false,
    showMoneySelector: false,
    minMoney1: '',
    maxMoney1: '',
    minMoney2: '',
    maxMoney2: '',
    orderTotal: 0,
    orderList: [],
    orderEnd: false,
    doneTotal: 0,
    doneList: [],
    doneEnd: false,
    userInfo: {
      userName: '',
      nickName: '',
      userAvatar: '',
      stationIndex: '',
      stationName: ''
    },
    showStationConfim: false,
    showStationErr: false,
    showSubmitInfo: false
    // 2022.2.21 微信回收open-type 能力
    // canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log('load')
    wx.setNavigationBarTitle({
      title: '订单'
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // console.log('show')
    this.setData({
      userInfo: wx.getStorageSync('userInfo'),
      stationList: wx.getStorageSync('userInfo').stationList,
      stationSelected: wx.getStorageSync('userInfo').stationSelected
    })
    if (wx.getStorageSync('tempTabId')) {
      this.tabChange(wx.getStorageSync('tempTabId'), 'fresh')
      wx.removeStorageSync('tempTabId')
    }
    // console.log(wx.getStorageSync('checkStationFlag'))
    // 初次进入需要确认站点 
    if (wx.getStorageSync('checkStationFlag')) {
      wx.removeStorageSync('checkStationFlag')
      if (wx.getStorageSync('userInfo').stationList && !wx.getStorageSync('userInfo').stationSelected) {
        // 有虚拟子站点，且需要选择站点，展示选择站点弹窗
        this.setData({ showStationSelector: true })
      } else {
        // 展示确认站点弹窗
        this.setData({ showStationConfim: true })
      }
    } else {
      if (this.data.stationSelected) {
        this.initData()
      } else {
        this.setData({ showStationSelector: true })
      }
    }

    // 关闭了站点确认和站点选择
    // if (!this.data.showStationConfim && !this.data.showStationSelector) {
    //   this.initData()
    // }
  },
  initData() {
    if (wx.getStorageSync('userInfo').stationList) {
      // 有虚拟子站点，已选择了虚拟子站点
      let tempList = wx.getStorageSync('userInfo').stationList
      let tempStationNo = wx.getStorageSync('userInfo').stationNo
      let tempIndex = tempList.findIndex(item => {
        return item.stationNo === tempStationNo
      })
      this.setData({ stationIndex: tempIndex })
    }

    this.fetchBagList()
    this.setData({
      ['queryOrder.startId']: '',
      ['queryDone.startId']: '',
      orderList: [],
      doneList: [],
      orderEnd: false,
      doneEnd: false,
    })

    this.fetchOrderCount()
    this.fetchOrderList()
    this.fetchDoneList()
    if (wx.getStorageSync('tempTabId')) {
      this.tabChange(wx.getStorageSync('tempTabId'), 'fresh')
      wx.removeStorageSync('tempTabId')
    }
  },
  /**
   * 获取箱包列表
   */
  fetchBagList() {
    request('/smsk/wechat/baginfo/bags', 'GET').then(res => {
      // console.log(res.data)
      if (res.data.code == 0) {
        let tempMoney = 0
        let tempList = res.data.data
        for (let i = 0; i < tempList.length; i++) {
          tempMoney = tempMoney + tempList[i].inputAmount
          tempList[i].inputAmount = tempList[i].inputAmount.toFixed(2)
          tempList[i].realCashAmount = tempList[i].realCashAmount.toFixed(2)
        }
        this.setData({
          bagList: tempList,
          sumMoney: tempMoney.toFixed(2)
        })
      } else {
        console.log(res)
      }
    })
  },
  /**
   * 删除箱包
   */
  handleDelete(e) {
    Dialog.confirm({
      message: '是否要删除该箱包？',
      confirmButtonText: '是',
      cancelButtonText: '否'
    }).then(() => {
      request('/smsk/wechat/baginfo/delete', 'POST', { id: this.data.bagList[e.currentTarget.id].id }).then(res => {
        console.log(res.data)
        if (res.data.code == 0) {
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
          this.fetchBagList()
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
      })
    }).catch(() => {
      // on cancel
    })

    // request('/smsk/wechat/baginfo/delete', 'POST', { id: this.data.bagList[e.currentTarget.id].id }).then(res => {
    //   console.log(res.data)
    //   if (res.data.code == 0) {
    //     wx.showToast({
    //       title: '删除成功',
    //       icon: 'success'
    //     })
    //     this.fetchBagList()
    //   } else {
    //     wx.showToast({
    //       title: res.data.message,
    //       icon: 'none'
    //     })
    //   }
    // })
  },
  /**
   * 编辑箱包
   */
  handleEdit(e) {
    let bagInfo = JSON.stringify(this.data.bagList[e.currentTarget.id])
    wx.navigateTo({
      url: '/pages/cashService/operator/bagFillin/bagFillin?bagInfo=' + bagInfo,
    })
  },
  /**
   * 点击“确认无误，发送”
   */
  send2Bank() {
    if (this.data.bagList.length == 0) {
      return
    }
    let tempIds = []
    this.data.bagList.forEach(item => {
      tempIds.push(item.id)
    })
    request('/smsk/wechat/orderinfo/submit', 'POST', { ids: tempIds }).then(res => {
      console.log(res.data)
      if (res.data.code === 0) {
        wx.showToast({
          title: '提交成功',
          icon: 'success'
        })
        this.initData()
      }
    })
  },
  // 点击“发送银行”，展示提示窗
  showSubmitInfo() {
    if (this.data.bagList.length == 0) {
      return
    }
    this.setData({ showSubmitInfo: true })
    return
  },
  // 关闭发送提示窗
  onSubmitInfoClose() {
    this.setData({ showSubmitInfo: false })
  },
  /**
   * 获取运行中订单列表
   */
  fetchOrderList() {
    if (this.data.orderEnd) {
      return
    }
    request('/smsk/wechat/orderinfo/list', 'GET', this.data.queryOrder).then(res => {
      // console.log(res.data)
      if (res.data.code == 0) {
        let tempList = this.data.orderList
        res.data.data.forEach(item => {
          tempList.push(item)
        })
        if (tempList.length > 0) {
          this.setData({
            orderList: tempList,
            ['queryOrder.startId']: tempList[tempList.length - 1].id,
            orderEnd: tempList.length < 10 ? true : false
          })
        }
      } else {
        console.log(res)
      }
    })
  },
  /**
   * 获取已完成订单列表
   */
  fetchDoneList() {
    if (this.data.doneEnd) {
      return
    }
    request('/smsk/wechat/orderinfo/list', 'GET', this.data.queryDone).then(res => {
      // console.log(res.data)
      if (res.data.code == 0) {
        let tempList = this.data.doneList
        res.data.data.forEach(item => {
          tempList.push(item)
        })
        if (tempList.length > 0) {
          this.setData({
            doneList: tempList,
            ['queryDone.startId']: tempList[tempList.length - 1].id
          })
        }
        // todo 做一个列表结束的标记
      } else {
        console.log(res)
      }
    })
  },
  /**
   * 获取订单数
   */
  fetchOrderCount() {
    request('/smsk/wechat/orderinfo/total', 'GET').then(res => {
      if (res.data.code === 0) {
        this.setData({
          orderTotal: res.data.data.runningCount,
          doneTotal: res.data.data.doneCount
        })
      } else {
        console.log(res)
      }
    })
  },
  /**
   * 切换底部tab
   */
  tabChange(e, str) {
    var that = this
    if (str == 'fresh') {
      // 手动刷新，获取tab组件，修改tab选中态
      this.selectComponent("#tabBar").switchTab(e, 'manual');
    } else {
      // 扫码
      if (e.detail.id == '1') {
        // wx.scanCode({
        //   success(res) {
        //     console.log(res)
        //     wx.showToast({
        //       title: '查询中',
        //       icon: 'loading'
        //     })
        //     var tempQrcode = res.result
        //     request('/smsk/wechat/baginfo/qrcode', 'GET', { code: tempQrcode }).then(res => {
        //       // console.log(res.data)
        //       if (res.data.code == 0) {
        //         if (res.data.data == null) {
                  wx.navigateTo({
                    url: '/pages/cashService/operator/bagFillin/bagFillin?newBag=true',
                  })
        //         } else {
        //           // 根据bagStatus判断箱包是否生成了订单
        //           if (res.data.data.bagsStatus === 'S') {
        //             // 跳转箱包编辑页
        //             let bagInfo = JSON.stringify(res.data.data)
        //             wx.navigateTo({
        //               url: '/pages/cashService/operator/bagFillin/bagFillin?bagInfo=' + bagInfo,
        //             })
        //           } else if (res.data.data.bagsStatus === 'D') {
        //             // TODO 箱包删除，临时码不可再用/永久码可以再用
        //             wx.showToast({
        //               title: '该二维码已使用',
        //               icon: 'none'
        //             })
        //           }
        //           else {
        //             // 跳转订单页
        //             wx.navigateTo({
        //               url: '/pages/cashService/operator/orderDetail/orderDetail?orderId=' + res.data.data.orderId,
        //             })
        //           }
        //         }
        //       } else {
        //         wx.showToast({
        //           title: res.data.message,
        //           icon: 'none'
        //         })
        //       }
        //     })
        //   },
        //   fail(res) {
        //     wx.showToast({
        //       title: '扫码失败',
        //       icon: 'error'
        //     })
        //   }
        // })
      } else if (e.detail.id == '0') {
        this.setData({
          tabActive: e.detail.id
        })
      } else if (e.detail.id == '2') {
        this.setData({
          tabActive: e.detail.id
        })
        this.setData({
          ['queryOrder.startId']: '',
          ['queryDone.startId']: '',
          orderList: [],
          doneList: [],
          orderEnd: false,
          doneEnd: false,
        })
        this.fetchOrderCount()
        this.fetchOrderList()
        this.fetchDoneList()
      }
    }
  },
  /**
   * 展示日期选择器
   */
  selectTime(e) {
    // console.log(e.currentTarget.dataset.mode)
    this.setData({
      showTimeSelector: true,
      selectMode: e.currentTarget.dataset.mode
    })
  },
  /**
   * 关闭日期选择器
   */
  onCloseTime(e) {
    this.setData({
      showTimeSelector: false,
      selectMode: ''
    })
  },
  /**
   * 设置选择的日期
   */
  onConfirmTime(event) {
    const [start, end] = event.detail;
    this.setData({
      showTimeSelector: false,
      [this.data.selectMode + '.date']: `${this.formatDateMD(start)} - ${this.formatDateMD(end)}`,
      [this.data.selectMode + '.minDate']: `${this.formatDateYMD(start)}`,
      [this.data.selectMode + '.maxDate']: `${this.formatDateYMD(end)}`,
    });
    if (this.data.selectMode === 'queryOrder') {
      this.setData({ ['queryOrder.startId']: '', orderList: [], orderEnd: false })
      this.fetchOrderList()
    } else {
      this.setData({ ['queryDone.startId']: '', doneList: [], doneEnd: false })
      this.fetchDoneList()
    }
  },
  formatDateMD(date) {
    date = new Date(date);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  },
  formatDateYMD(date) {
    date = new Date(date);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  },
  /**
   * 清空日期筛选
   */
  cleanDate(e) {
    this.setData({
      [e.currentTarget.dataset.mode + '.date']: '',
      [e.currentTarget.dataset.mode + '.minDate']: '',
      [e.currentTarget.dataset.mode + '.maxDate']: '',
    })
    if (e.currentTarget.dataset.mode === 'queryOrder') {
      this.setData({ ['queryOrder.startId']: '', orderList: [], orderEnd: false })
      this.fetchOrderList()
    } else {
      this.setData({ ['queryDone.startId']: '', doneList: [], doneEnd: false })
      this.fetchDoneList()
    }
  },
  /**
   * 展示金额填写框
   */
  selectMoney(e) {
    this.setData({
      showMoneySelector: true,
      selectMode: e.currentTarget.dataset.mode
    })
  },
  /**
   * 关闭金额填写框
   */
  onCloseMoney() {
    this.setData({
      showMoneySelector: false,
      selectMode: ''
    })
  },
  /**
   * 清空填写金额
   */
  cleanMoney(e) {
    if (e.currentTarget.dataset.mode === 'queryOrder') {
      this.setData({
        minMoney1: '',
        maxMoney1: '',
        ['queryOrder.minMoney']: '',
        ['queryOrder.maxMoney']: '',
      })
      this.setData({ ['queryOrder.startId']: '', orderList: [], orderEnd: false })
      this.fetchOrderList()
    } else {
      this.setData({
        minMoney2: '',
        maxMoney2: '',
        ['queryDone.minMoney']: '',
        ['queryDone.maxMoney']: '',
      })
      this.setData({ ['queryDone.startId']: '', doneList: [], doneEnd: false })
      this.fetchDoneList()
    }
  },
  /**
   * 确认填写金额
   */
  onConfirmMoney(e) {
    let mode = this.data.selectMode
    this.setData({
      [this.data.selectMode + '.minMoney']: this.data.selectMode === 'queryOrder' ? this.data.minMoney1 : this.data.minMoney2,
      [this.data.selectMode + '.maxMoney']: this.data.selectMode === 'queryOrder' ? this.data.maxMoney1 : this.data.maxMoney2,
      showMoneySelector: false,
      selectMode: ''
    })
    // 刷新list
    if (mode === 'queryOrder') {
      this.setData({ ['queryOrder.startId']: '', orderList: [], orderEnd: false })
      this.fetchOrderList()
    } else {
      this.setData({ ['queryDone.startId']: '', doneList: [], doneEnd: false })
      this.fetchDoneList()
    }
  },

  // 多选(无用)
  onChange(event) {
    // 计算合计金额
    let tempMoney = 0
    for (let i = 0; i < event.detail.length; i++) {
      tempMoney += this.data.bagList[event.detail[i]].inputAmount
    }
    this.setData({
      result: event.detail,
      sumMoney: tempMoney
    });
    // 联动全选标记
    if (this.data.result.length == this.data.bagList.length) {
      this.setData({
        allChecked: true,
      })
    } else {
      this.setData({
        allChecked: false,
      })
    }
  },
  // 全选
  onPickAll(event) {
    let tempResult = []
    let tempMoney = 0
    if (event.detail) {
      for (let i = 0; i < this.data.bagList.length; i++) {
        tempResult.push(i + '')
        tempMoney += this.data.bagList[i].inputAmount
        let tempStr = 'bagList[' + i + '].picked'
        this.setData({
          [tempStr]: event.detail
        })
      }
    } else {
      for (let i = 0; i < this.data.bagList.length; i++) {
        let tempStr = 'bagList[' + i + '].picked'
        this.setData({
          [tempStr]: event.detail
        })
      }
    }
    this.setData({
      allChecked: event.detail,
      result: tempResult,
      sumMoney: tempMoney
    });
  },

  pickBag(e) {
    let tempId = this.data.result.indexOf(e.currentTarget.id)
    let tempArr = this.data.result
    let tempStr = 'bagList[' + e.currentTarget.id + '].picked'
    if (tempId != -1) {
      tempArr.splice(tempId, 1)
      this.setData({
        result: tempArr,
        [tempStr]: false
      })
    } else {
      tempArr.push(e.currentTarget.id)
      this.setData({
        result: tempArr,
        [tempStr]: true
      })
    }
    // 计算合计金额
    let tempMoney = 0
    for (let i = 0; i < this.data.result.length; i++) {
      tempMoney += this.data.bagList[this.data.result[i]].inputAmount
    }
    this.setData({
      sumMoney: tempMoney
    });
    // 联动全选标记
    if (this.data.result.length == this.data.bagList.length) {
      this.setData({
        allChecked: true,
      })
    } else {
      this.setData({
        allChecked: false,
      })
    }
  },
  userTabChange(e) {
    this.setData({
      userActive: e.currentTarget.id
    })
  },
  fetchOrderDetail(e) {
    // console.log(e.currentTarget.id)
    wx.navigateTo({
      url: '/pages/cashService/operator/orderDetail/orderDetail?orderId=' + e.currentTarget.id,
    })
  },
  logout() {
    request('/smsk/wechat/auth/logout', 'POST').then(res => {
      console.log(res.data)
      if (res.data.code == 0) {
        wx.setStorageSync('userInfo', res.data.data)
        wx.setStorageSync('token', res.data.data.token)
        wx.redirectTo({
          url: '/pages/cashService/roleSelection/roleSelection',
        })
        // todo 页面层次有点问题
      } else {
        this.showToast(res.data.message)
      }
    })
  },
  onChangeRadio(event) {
    this.setData({
      stationIndex: event.detail,
    });
  },
  onClickRadio(event) {
    const { name } = event.currentTarget.dataset;
    this.setData({
      stationIndex: name,
    });
  },
  // 站点列表选择站点
  confirmStation() {
    var that = this
    request('/smsk/wechat/auth/station', 'POST', { id: this.data.stationList[this.data.stationIndex].stationId }).then(res => {
      console.log(res.data)
      if (res.data.code === 0) {
        wx.setStorageSync('userInfo', res.data.data)
        wx.setStorageSync('token', res.data.data.token)
        this.setData({
          showStationSelector: false,
          userInfo: wx.getStorageSync('userInfo'),
        })
        this.initData()
        if (wx.getStorageSync('tempTabId')) {
          this.tabChange(wx.getStorageSync('tempTabId'), 'fresh')
          wx.removeStorageSync('tempTabId')
        }
      }
    })
  },
  // 切换站点
  switchStation() {
    if (this.data.stationList && this.data.stationList.length > 1) {
      this.setData({ showStationSelector: true })
      wx.setStorageSync('tempTabId', '2')
    }
  },
  // 确认站点
  checkStation(e) {
    // console.log(e.currentTarget.dataset.result)
    if (e.currentTarget.dataset.result == 'true') {
      // 站点无误
      this.setData({ showStationConfim: false })
      this.initData()
      if (wx.getStorageSync('tempTabId')) {
        this.tabChange(wx.getStorageSync('tempTabId'), 'fresh')
        wx.removeStorageSync('tempTabId')
      }
    } else {
      // 站点有误
      this.setData({ showStationErr: true })
    }
  },
  // 站点信息不符，退回上一页
  checkStationErr() {
    wx.navigateBack({
      delta: -1,
    })
  }
})